package com.mojo.openapi.controller;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class HmacSignatureExample {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        String secretId = "assignedSecretId";
        String secretKey = "your-secret-key"; // 应保持保密
        String data = "code=B123&companyName=CompanyX&secretId=assignedSecretId"; // 待签名数据

        // 按照ASCII码表的顺序对参数进行排序
        Map<String, String> params = new TreeMap<>(); // 自然排序
        String[] dataParts = data.split("&");
        for (String part : dataParts) {
            String[] keyValue = part.split("=");
            params.put(keyValue[0], keyValue[1]);
        }
        StringBuilder sortedData = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sortedData.append(entry.getKey());
            sortedData.append("=");
            sortedData.append(entry.getValue());
            sortedData.append("&");
        }
        sortedData.deleteCharAt(sortedData.length() - 1); // 移除最后一个'&'

        // 使用HMAC-SHA256算法生成签名
        Key key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] hash = mac.doFinal(sortedData.toString().getBytes(StandardCharsets.UTF_8));

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder(0);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        // 打印签名
        System.out.println("HMAC-SHA256 Signature: " + hexString.toString());
    }
}